from flask import Blueprint,render_template,jsonify,request
from models.entity.department import Department
from models.entity.organization import Organization
from models.entity.quarter import Quarter
from models.entity.user import User
import json
from sqlalchemy import or_
from utils.result import result

mod = Blueprint("department", __name__, url_prefix="/core/department", template_folder="templates", static_folder="static")

@mod.route("/get_all/",methods=["POST"])
def get_department_all_interface():
    """
    以平铺方式返回所有部门的json列表
    """
    # return: json
    # [
    #       {
    #               id: id,
    #               name: 'name',
    #               code: 'code',
    #               description: 'description',
    #               org_id: org_id(int),
    #               ParentId: parent_id(int)(表示该部门直属于某机构),
    #               path: 'path',
    #               Level: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #               child_num: child_num(int),
    #               dis_order: dis_order(int),
    #               status: status(int),(0表示该部门在系统中正常,1表示该部门在系统中被禁用)
    #               character: "character",
    #               abbreviation: "abbreviation",
    #               extension_number: "extension_number",
    #               person_in_charge: "person_in_charge"
    #       }, ...
    # ]
    rlist=[]
    for item in Department().get_list_all():
        t_dic=Department.to_dict(item)
        rlist.append(t_dic)
    return result(data=rlist)

@mod.route("/get_tree_all/",methods=["POST","GET"])
def get_department_tree_all_interface():
    """
    以嵌套形式返回所有部门的json列表,没有用，不知道用过没有
    """
    # return: json
    # [
    #       {
    #               id: id,
    #               name: "name",
    #               code: "code",
    #               description: "description",
    #               org_id: org_id(int),
    #               ParentId: parent_id(int)(0表示该部门直属于某机构),
    #               path: 'path',
    #               Level: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #               child_num: child_num(int),
    #               dis_order: dis_order(int),
    #               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #               character: "character",
    #               abbreviation: "abbreviation",
    #               extension_number: "extension_number",
    #               person_in_charge: "person_in_charge",
    #               children: [{
    #                                               id: "id",
    #                                               name: "name",
    #                                               code: "code",
    #                                               description: "description",
    #                                               org_id: org_id(int),
    #                                               ParentId: parent_id(int)(-1表示该部门直属于某机构),
    #                                               path: "path",
    #                                               Level: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #                                               child_num: child_num(int),
    #                                               dis_order: dis_order(int),
    #                                               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #                                               character: "character",
    #                                               abbreviation: "abbreviation",
    #                                               extension_number: "extension_number",
    #                                               person_in_charge: "person_in_charge",
    #                                               children=[...]
    #                                       }, ...]
    #       }, ...
    # ]
    rlist=[]
    root_department_list=Department.get_first_level_departments()
    print('root_department_list', root_department_list)
    for item in root_department_list:
        rdic = item.to_dict()
        rdic["children"] = Department().get_tree_by_pid(item.id)
        print('rdic["children"]', rdic["children"])
        rlist.append(rdic)
    return result(success=1, data=rlist)


@mod.route("/get_all_by_organization_id/",methods=["POST","GET"])
def get_department_all_by_organization_interface():
    """
    以json列表的形式返回所有某个机构下的部门
    """
    rlist=[]
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg='格式错误',data=rlist)
    if "id" in data:
        the_organization=Organization().get_entity_by_id(data["id"])
    else:
        return result(success=0,error_code=-2,error_msg="机构不存在",data=rlist)
    if the_organization is None:
        return result(success=0,error_code=-3,error_msg="机构不存在",data=rlist)
    all_departments=Department.get_departments_all_by_organization(the_organization)
    for item in all_departments:
        rlist.append(item.to_dict())
    return result(success=1, data=rlist)


@mod.route("/get_tree_by_organization_id/",methods=["POST","GET"])
def get_department_tree_by_organization_interface():
    """
    以json嵌套列表的形式返回所有某个机构下的部门
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # [
    #       {
    #               id: id,
    #               name: "name",
    #               code: "code",
    #               description: "description",
    #               org_id: org_id(int),
    #               parent_id: parent_id(int)(-1表示该部门直属于某机构),
    #               path: 'path',
    #               depth: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #               child_num: child_num(int),
    #               dis_order: dis_order(int),
    #               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #               character: "character",
    #               abbreviation: "abbreviation",
    #               extension_number: "extension_number",
    #               person_in_charge: "person_in_charge",
    #               children: [{
    #                                               id: "id",
    #                                               name: "name",
    #                                               code: "code",
    #                                               description: "description",
    #                                               org_id: org_id(int),
    #                                               parent_id: parent_id(int)(-1表示该部门直属于某机构),
    #                                               path: "path",
    #                                               depth: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #                                               child_num: child_num(int),
    #                                               dis_order: dis_order(int),
    #                                               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #                                               character: "character",
    #                                               abbreviation: "abbreviation",
    #                                               extension_number: "extension_number",
    #                                               person_in_charge: "person_in_charge",
    #                                               children=[...]
    #                                       }, ...]
    #       }, ...
    # ]
    rlist=[]
    try:
        data=json.loads(bytes.decode(request.data))
    except:
        # print(request.data.decode("utf-8"))
        return result( success=0, error_code=-1,error_msg="json format error")
    if "id" in data:
        the_organization=Organization().get_entity_by_id(data["id"])
    else:
        return result( success=0,error_code=-2,error_msg="key id is not in the json")
    if the_organization is None:
        return result( success=0,error_code=-3,error_msg="the org_id is not exist")
    all_departments=Department.get_departments_by_organization(the_organization)
    for item in all_departments:
        rdic = item.to_dict()
        rdic["children"] = Department().get_tree_by_pid(item.id)
        rlist.append(rdic)
    return result(success=1, data=rlist)


@mod.route("/get_tree_by_department_id/",methods=["POST"])
def get_department_tree_by_id_interface():
    """
    根据部门id获取此部门及其下属部门组成的json嵌套列表
    """
    # request: json
    # {
    #       department_id: department_id
    # }
    # return: json
    # [
    #       {
    #               id: id,
    #               name: "name",
    #               code: "code",
    #               description: "description",
    #               org_id: org_id(int),
    #               parent_id: parent_id(int)(-1表示该部门直属于某机构),
    #               path: 'path',
    #               depth: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #               child_num: child_num(int),
    #               dis_order: dis_order(int),
    #               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #               character: "character",
    #               abbreviation: "abbreviation",
    #               extension_number: "extension_number",
    #               person_in_charge: "person_in_charge",
    #               children: [{
    #                                               id: "id",
    #                                               name: "name",
    #                                               code: "code",
    #                                               description: "description",
    #                                               org_id: org_id(int),
    #                                               parent_id: parent_id(int)(-1表示该部门直属于某机构),
    #                                               path: "path",
    #                                               depth: depth(int)(从0开始计算,0表示该部门为某个机构的直属部门),
    #                                               child_num: child_num(int),
    #                                               dis_order: dis_order(int),
    #                                               status: status(int)(0表示该部门在系统中正常,1表示该部门在系统中被禁用),
    #                                               character: "character",
    #                                               abbreviation: "abbreviation",
    #                                               extension_number: "extension_number",
    #                                               person_in_charge: "person_in_charge"
    #                                               children=[...]
    #                                       }, ...]
    #       }, ...
    # ]
    rlist=[]
    try:
        data=json.loads(bytes.decode(request.data))
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    if "department_id" in data:
        the_department=Department().get_entity_by_id(data["department_id"])
    else:
        return result(success=0,error_code=-2,error_msg="key department_id is not in the json")
    if the_department is None:
        return result(success=0, error_code=-3,error_msg="the department_id is not exist")
    rlist=Department().get_tree_by_pid(the_department.id)
    return result(success=1,error_code=None,error_msg=None,data=rlist)

@mod.route("/get_by_department_id/",methods=["POST"])
def get_department_by_id_interface():
    """
    根据部门id获取保存该部门的信息的json对象
    """
    # request: json
    # {
    #       id: id
    # }
    # return json:
    # {
    #       id: id,
    #       name: "name",
    #       code: "code",
    #       description: "description",
    #       org_id: org_id,
    #       parent_id: parent_id,
    #       path: "path",
    #       depth: depth,
    #       child_num: child_num,
    #       dis_order: dis_order,
    #       status: status,
    #       character: "character",
    #       abbreviation: "abbreviation",
    #       extension_number: "extension_number",
    #       person_in_charge: "person_in_charge"
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    if "id" in data:
        the_department=Department().get_entity_by_id(data["id"])
    else:
        return result(success=0,error_code=-2,error_msg="key department_id is not in the json")
    if the_department is None:
        return result( success=0,error_code=-3,error_msg="the department_id is not exist")
    t_dic=the_department.to_dict()
    return result(success=1,error_code=None, error_msg=None,data=t_dic)

@mod.route("/edit/",methods=["POST"])
def edit_department_interface():
    """
    修改部门信息
    """
    # request: json
    # {
    #       id: id,
    #       name: "name",
    #       code: "code",
    #       description: "description",
    #       org_id: org_id,
    #       parent_id: parent_id,
    #       dis_order: dis_order,
    #       status: status,
    #       character: "character",
    #       abbreviation: "abbreviation",
    #       extension_number: "extension_number",
    #       person_in_charge: "person_in_charge"
    # }
    # return: json
    # {
    #       success: 0|1, (0代表修改失败,1代表修改成功)
    #       error_code: error_code, (通常为负数,当success为0时存在)
    #       error_msg: "error_msg", (描述错误原因,当success为0时存在)
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1,error_msg="json format error")
    the_department = Department().get_entity_by_id(data["id"])
    if the_department.org_id!= data['org_id']:
        return result(success=0, error_code=-2, error_msg="请不要随意调换该部门位置")
    if the_department.name != data['name'] and Department.query.filter_by(name=data['name']).filter_by(org_id=data['org_id']).first():
        return result(success=0, error_code=-2, error_msg="该部门已经存在")
    if the_department.code != data['code'] and Department.get_department_by_code(data['code']):
        return result(success=0, error_code=-2, error_msg="该编码已经存在")
    try:
        the_department.from_dict(data)
    except:
        return result( success=0, error_code=-2, error_msg="数据不完整，格式错误")
    the_department.save()
    return result(success=1,error_code=None, error_msg=None)

@mod.route("/del/",methods=["POST"])
def delete_department_by_id_interface():
    """
    通过部门id删除指定部门
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # {
    #       success: 0|1 (0代表修改失败,1代表修改成功)
    #       error_code: error_code (通常为负数,当success为0时存在)
    #       error_msg: "error_msg" (描述错误原因,当success为0时存在)
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0,error_code=-1,error_msg="数据格式错误")
    if not "id" in data:
        return result(success=0,error_code=-2,error_msg="数据不完整")
    department_id=data["id"]
    the_department=Department().get_entity_by_id(department_id)
    if the_department:
        if len(Department().get_list_by_pid(department_id)) >0:
            return result(success=0,error_code=-3,error_msg="此部门仍然具有下属部门")
        if len(User.get_users_by_department_id(the_department.id))>0:
            return result(success=0,error_code=-4,error_msg="此部门仍然具有用户")
        if len(Quarter.get_all_quarters_by_department_id(the_department.id))>0:
            return result(success=0, error_code=-4, error_msg="此部门仍然有岗位")
        try:
            ret=the_department.delete()
            print('ret', ret)
        except RuntimeError as e:
            return result(success=0,error_code=-4,error_msg=e)
        if ret==True:
            return result(success=1)
        else:
            return result(success=0, error_code=-5, error_msg="未知错误")
            # return result(success=0,error_code=-5, error_msg="存在子节点")
    else:
        return result(success=0,error_code=-7, error_msg="该部门异常...")

@mod.route("/add/",methods=["POST"])
def add_department_interface():
    """
    增加部门
    """
    # request:
    # {
    #       // 若可选项不填则不写这个键
    #       name: "name",
    #       code: "code",
    #       description: "description"(可选),
    #       org_id: org_id,
    #       parent_id: parent_id,(若为顶级部门则没有此键)
    #       dis_order: dis_order(可选),
    #       status: status(0|1: 0表示该部门在系统中正常, 1表示该部门在系统中被禁用),
    #       character: "character",
    #       abbreviation: "abbreviation",
    #       extension_number: "extension_number",
    #       person_in_charge: "person_in_charge"
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
        print('data', data)

        #{'name': '13', 'dis_order': 0, 'org_id': 1, 'abbreviation': '1', 'character': '协调性', 'parent_id': 0,
         #'person_in_charge': '', 'status': 0, 'code': '13', 'description': '', 'email': '', 'phone_number': ''}

    except:
        return result(success=0,error_code=-1,error_msg="数据格式错误")
    new_department=Department()
    if not Department.get_department_by_code(data['code']) is None:
        return result(success=0,error_code=-3,error_msg="部门编号已被占用")
    if Department.query.filter_by(name=data['name']).filter_by(org_id=data['org_id']).first():
        return result( success=0, error_code=-4,error_msg="部门名称已被占用")
    new_department.parent_id=data['parent_id']
    if new_department.parent_id == 0:
        # 如果parent_id等于0
        if "org_id" in data:
            if data["org_id"] is None:
                return result(success=0,error_code=-5,error_msg="parent_id和org_id不可同时为空")
            if Organization.get_organization_by_id(data["org_id"]) is None:
                return result(success=0,error_code=-6,error_msg="机构不存在")
            else:
                new_department.org_id=data["org_id"]
        else:
            return result(success=0,error_code=-7,error_msg="org_id和parent_id均不存在于json中")
    else:
        # 如果parent_id不为None
        if not "org_id" in data:
            # 如果org_id不存在于data中
            return result(success=0, error_code=-9,error_msg="parent_id存在于json中但org_id不在json中")
        else:
            # 如果org_id存在于data中
            parent_department=Department().get_entity_by_id(new_department.parent_id)
            if parent_department.org_id!=data["org_id"]:
                return result(success=0, error_code=-10, error_msg="parent_id所代表的部门不隶属于org_id所代表的机构下")
            else:
                new_department.org_id=data["org_id"]
    try:
        new_department.from_dict(data)
    except RuntimeError as e:
        return result(success=0,error_code=-1,error_msg=e)

    if new_department.save():
        return result(success=1)
    else:
        return result(success=0,error_code=-8,error_msg="save error")


@mod.route("/search/",methods=["POST"])
def search_department():
    """
    查询button
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        # receive = request.get_data()
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            return result(success=0, error_code=-9, error_msg="数据格式错误")
        departments = Department.search(query_word)
        return result(success=1, error_code=None, error_msg=None,data=departments)